package com.tcl.aota.admin.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tcl.aota.admin.dto.CurefObj;
import com.tcl.aota.common.utils.StringUtil;
import org.apache.log4j.Logger;

import javax.xml.soap.*;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

/**
 * CU工具类
 *
 * @author kelong
 * @date 5/12/15
 */
public class CuUtil {
    public static Logger LOG = Logger.getLogger(CuUtil.class);


    /**
     * webService获取Cu
     *
     * @return
     */
    public static List<CurefObj> getCu() {
        //服务的地址
        HttpURLConnection conn = null;
        OutputStream os = null;
        InputStream is = null;
        List<CurefObj> curefObjs = null;
        try {
            URL wsUrl = new URL("http://180.169.5.242:8081/all_cu_info.php");
            conn = (HttpURLConnection) wsUrl.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
            os = conn.getOutputStream();
            //请求体
            String soap =
                "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:q0=\"http://ws.itcast.cn/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"
                    +
                    "<soapenv:Body> <q0:all_cu><arg0>admin_cu</arg0><arg1>password_all_cu</arg1></q0:all_cu> </soapenv:Body> </soapenv:Envelope>";
            os.write(soap.getBytes());
            is = conn.getInputStream();
            byte[] b = new byte[1024];
            int len = 0;
            String s = "";
            while ((len = is.read(b)) != -1) {
                String ss = new String(b, 0, len, "UTF-8");
                s += ss;
            }
            curefObjs = CuUtil.parseCu(s);
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        } finally {
            try {
                is.close();
                os.close();
                conn.disconnect();
            } catch (IOException e) {
            }
        }
        return curefObjs;
    }

    /**
     * 解析为curefObj对象
     *
     * @param soapString
     * @return
     */
    private static List<CurefObj> parseCu(String soapString) {
        List<CurefObj> curefObjs = new ArrayList<>();
        try {
            String jsonData = parseSoapXml(soapString);
            JSONObject jsonObject = JSON.parseObject(jsonData);
            String status = StringUtil.obj2Str(jsonObject.get("status"));
            if (!"1".equals(status)) {
                return null;
            }
            jsonObject.remove("status");
            Set<Map.Entry<String,Object>> cuSet=jsonObject.entrySet();
            for(Map.Entry<String,Object> entry:cuSet){
                long id = StringUtil.obj2Long(entry.getKey());
                JSONObject curefData = (JSONObject)entry.getValue();
                String product = curefData.getString("productfamily_name");
                String curefregexp = curefData.getString("productclass_curefregexp");
                String curef = curefData.getString("productinstance_curef");
                String userName = curefData.getString("user_name");
                CurefObj curefObj = new CurefObj(id, product, curefregexp, curef, userName);
                if (curefObj.isVaild()) {
                    curefObjs.add(curefObj);
                }
            }
            LOG.info("get cu from fota:" + curefObjs.size());
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return curefObjs;
    }


    /**
     * 解析soapMessage消息
     *
     * @param soapString:soapMessage xml data
     * @return
     */
    private static String parseSoapXml(String soapString) {
        String messageText = null;
        try {
            MessageFactory msgFactory = MessageFactory.newInstance();
            SOAPMessage reqMsg = msgFactory.createMessage(new MimeHeaders(),
                new ByteArrayInputStream(soapString.getBytes("UTF-8")));
            reqMsg.saveChanges();
            SOAPBody body = reqMsg.getSOAPBody();
            Node bodyNode = (Node) body.getFirstChild();
            Node responseNode = (Node) bodyNode.getFirstChild();
            Node cuNode = (Node) responseNode.getFirstChild();
            messageText = cuNode.getNodeValue();
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return messageText;
    }
}
